package com.pawn.exceptiondemo.controller;

import com.pawn.exceptiondemo.entity.Order;
import com.pawn.exceptiondemo.exception.MyException;
import com.pawn.exceptiondemo.utils.ResCode;
import com.pawn.exceptiondemo.utils.ResUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * @program: springboot-1-cache
 * @description:
 * @author: Dawson.Zhang
 * @create: 2020-08-28
 **/
@RestController
@Slf4j
public class OrderController {
    public static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);

    /**
     *
     * @return
     */
    @GetMapping("/")
    public ResUtil hello() {
        LOGGER.info("接口接入时间[{}]", LocalDateTime.now());
        Order or = Order.builder().Id(100L).name("哈哈哈").build();
        try {
            if (true) {
                System.out.println("库存不足");
                throw new MyException("库存不足");
            }
        } catch (MyException e) {
            // try中如果抛出异常后，会在catch中继续抛出，最终会会exceptionHandler拦截。
             throw new MyException("库存不够了catch");
            // 如果是return掉的话，则不会触发ExceptionHandler直接返回给前台
            // return  ResUtil.FAILED(ResCode.FAILED);
        }
        return ResUtil.SUCCESS(ResCode.SUCCESS,or);
    }

    /**
     *
     * @return
     */
    @GetMapping("/er")
    public ResUtil error(@RequestParam("ID")String id) {
        LOGGER.info("接口接入时间[{}]", LocalDateTime.now());
        Order or = Order.builder().Id(100L).name("哈哈哈").build();
        if (true) {
            //throw抛出异常后，ControllerAdvice会自动捕获
            throw new MyException("库存不足");
        }
        return ResUtil.SUCCESS(ResCode.SUCCESS,or);
    }
}
